package com.leyou.user.controller;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.interceptors.LoginInterceptor;
import com.leyou.auth.utils.UserContext;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author GL160601@163.com
 * @date 2020/12/16 14:19
 */

@RestController
@RequestMapping("/info")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 判断信息是否存在(用户名或手机号)
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> dataIsExists(
            @PathVariable("data")String data,
            @PathVariable("type")Integer type) {
        return ResponseEntity.ok(this.userService.dataIsExists(data, type));
    }

    /**
     * 用户注册
     * @param user
     * @param code
     * @return
     */
    @PostMapping
    public ResponseEntity<Void> registUser(@Valid User user, @RequestParam("code")String code) {
        this.userService.registUser(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void> SendMsg(@RequestParam("phone") String phone) {
        userService.SendMsg(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }


    /**
     * 根据用户名和密码查询用户信息
     * @param username
     * @param password
     * @return
     */
    @GetMapping
    public ResponseEntity<UserDTO> queryUser(
            @RequestParam("username") String username,
            @RequestParam("password") String password) {
        return ResponseEntity.ok(this.userService.queryUser(username, password));
    }

    /**
     * 获取一个cookie名称叫LY_TOKEN
     * @param token
     * @return
     */
    @GetMapping("/me")
    public ResponseEntity<UserDetail> checkLogin(@CookieValue("LY_TOKEN")String token){
        return ResponseEntity.ok(UserContext.getUser());
    }
}
